/**
 * Created by apple on 2017/7/6.
 */

var postHelp = module.exports;
var http = require('http');
var querystring = require('querystring');
var Config = require('../config');


postHelp.jsonPost = function (host,path,port,contentsInfo,cb) {

    postHelp.post(host,path,port,contentsInfo,true,cb);

}

//cb(err,data)
postHelp.post = function (host,path,port,contentsInfo,isJson,cb) {

    if(!host || !path || !port || !contentsInfo || !isJson ){
        cb('方法参数不为空');
        return;
    }

    var contents = querystring.stringify(contentsInfo);

    var options = {

        host:host,
        path:path,
        port: port,
        method:'POST',
        headers:{
            'Content-Type':'application/x-www-form-urlencoded',
            'Content-Length':contents.length
        }
    }

    var req = http.request(options, function (res) {
        res.setEncoding('utf8');

        var jsonData;
        res.on('data',function (data) {

            if(jsonData){
                jsonData += data;
            }else {
                jsonData = data;
            }
        });
        res.on('end',function(){

            try {
                if (isJson == true) {//要求返回的是json数据

                    // console.log(jsonData);
                    if (jsonData.indexOf('<html') > 0) {
                        cb('数据格式有误');
                        return;
                    }
                    var res = JSON.parse(jsonData);
                    if (res.status == 200 && res.payload) {
                        cb(null, res.payload);
                    } else {
                        cb(res.err);
                    }
                } else {//要求返回的是xml数据
                    if (jsonData.indexOf('<html>') > 0) {
                        cb(null, jsonData);
                        return;
                    }
                    cb('数据格式有误');
                }
            }
            catch (e) {
                cb(e);
                console.log(e);
                return;
            }


        });
    });


    req.on('error',function(err){
        console.log(err);
        cb(err);
        return;
    });

    req.write(contents);
    req.end;

}



postHelp.baseRequest = function(host,port,path,param,callback) {
    var url = 'http://' + host + ':' + port + path + '?';
    for(var key in param){
        if(!param[key]) {
            continue;
        }
        url += key + '='  + param[key]  + '&';
    }
    url = url_encode(url.substr(0,url.length-1));
    var options = {
        url: url,
        method: 'POST'
    };
    request(options, function (error, response, body) {
        if (error && response && response.statusCode != 200 && !body) {
            callback('服务器异常，请稍后重试');
            console.log(error);
            return;
        } else {
            try {
                body = JSON.parse(body);
                if(body.status == 200){
                    callback(null,body.payload);
                    return;
                }
                console.log(body);
                callback(body.err);
            } catch (e) {
                callback('服务器异常，请稍后重试');
            }
        }
    });
}

function url_encode(url){
    url = encodeURIComponent(url);
    url = url.replace(/\%3A/g, ":");
    url = url.replace(/\%2F/g, "/");
    url = url.replace(/\%3F/g, "?");
    url = url.replace(/\%3D/g, "=");
    url = url.replace(/\%26/g, "&");

    return url;
}